<template>
    <div class="tools-video-record-page _page">
        <div class="wrap">
            <div class="option-item">
                <label>录制类型：</label>
                <div>
                    <input :disabled="isStart" type="radio" id="t1" value="t1" v-model="recordType"/><label for="t1">定时录制</label>
                    <input :disabled="isStart" type="radio" id="t2" value="t2" v-model="recordType"/><label for="t2">手动结束</label>
                </div>
            </div>
            <!-- <div class="option-item">
                <label>导出类型：</label>
                <div>
                    <input :disabled="isStart" type="radio" id="webm" value="webm" v-model="fileType"/><label for="webm">webm</label>
                    <input :disabled="isStart" type="radio" id="mp4" value="mp4" v-model="fileType"/><label for="mp4">mp4</label>
                </div>
            </div> -->
            <div class="option-item" v-show="recordType == 't1'">
                <label>录制时长：</label>
                <input :disabled="isStart" type="number" v-model.trim="duration"/>
                <span>秒</span>
            </div>
            <button @click="doHandle()">{{ isStart ? '结束' : '开始' }}录制{{ (recordType == 't1' && isStart) ? '('+surplusTime+'s)' : '' }}</button>
        </div>
    </div>
</template>

<script>
import { ref } from 'vue'
import { useToastStore } from '@/stores/toast'
// import { addFFmpeg } from '@/lib/util'

export default {
    setup () {
        const toast = useToastStore()
        const duration = ref(5)
        const recordType = ref('t1')
        let mediaRecorder = null
        let isStart = ref(false)
        let endTimer = null
        let surplusTime = ref(0)
        let ffmpeg = null
        const fileType = ref('webm')

        const doChangeToMp4 = async (blob, fileName) => {
            const inputFileName = fileName + '.webm'
            const outputFileName = fileName + '.mp4'
            const webmFile = new File([blob], inputFileName, { type: blob.type })
            
            ffmpeg.FS('writeFile', inputFileName, await fetchFile(webmFile))
            // 执行转换命令
            await ffmpeg.run('-i', inputFileName, '-c:v', 'copy', outputFileName)
            // 读取转换后的文件
            const resData = ffmpeg.FS('readFile', outputFileName)
            // 创建Blob
            const resblob = new Blob([resData.buffer], { type: 'video/mp4' })
            const url = URL.createObjectURL(resblob)
            const a = document.createElement('a')
            a.href = url
            a.download = outputFileName
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
        }

        const doStartRecord = async () => {
            const displayMediaOptions = {
                video: { cursor: 'always' },
                audio: { echoCancellation: true, noiseSuppression: true, sampleRate: 44100 },
            }
            const captureStream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions)
            const options = { mimeType: 'video/webm;codecs=vp9' }
            mediaRecorder = new MediaRecorder(captureStream, options)
            const recordedChunks = []
            mediaRecorder.ondataavailable = (event) => {
                if (event.data.size > 0) {
                    recordedChunks.push(event.data)
                }
            }
            mediaRecorder.onstart = () => {
                if (recordType.value == 't1') {
                    surplusTime.value = duration.value
                    endTimer = setInterval(() => {
                        surplusTime.value--
                        if (surplusTime.value <= 0) {
                            doEnd()
                        }
                    }, 1000)
                }
            }
            mediaRecorder.onstop = () => {
                const blob = new Blob(recordedChunks, { type: 'video/webm' })
                const fileName = `screen_recording_${Date.now()}`
                if (fileType.value == 'mp4') {
                    // doChangeToMp4(blob, fileName)
                } else {
                    const url = URL.createObjectURL(blob)
                    const a = document.createElement('a')
                    a.href = url
                    a.download = `${fileName}.webm`
                    document.body.appendChild(a)
                    a.click()
                    document.body.removeChild(a)
                }
            }
            mediaRecorder.start()
        }

        const doStart = async () => {
            if (recordType.value == 't1') {
                if (!duration.value || duration.value < 1) {
                    toast.warning('录制时长必须大于0')
                    return
                }
            }
            isStart.value = true
            doStartRecord()
        }

        const doEnd = () => {
            if (mediaRecorder && mediaRecorder.state !== 'inactive') {
                mediaRecorder.stop()
            }
            isStart.value = false
            surplusTime.value = 0
            if (endTimer) {
                clearInterval(endTimer)
                endTimer = null
            }
        }

        const doHandle = () => {
            if (!isStart.value) {
                doStart()
            } else {
                doEnd()
            }
        }

        // onMounted(async () => {
        //     await addFFmpeg()
        //     ffmpeg = new FFmpegWASM.FFmpeg()
        //     ffmpeg.on('log', (e) => {
        //         console.log(e.message)
        //     })
        //     await ffmpeg.load({ coreURL: './assets/ffmpeg-core.min.js' })
        // })

        return {
            duration,
            recordType,
            doHandle,
            isStart,
            surplusTime,
            fileType
        }
    }
}
</script>

<style lang="scss">
    @use './style.scss';
</style>